﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
using DBO.Utility;
using System.Net.Mail;
using BusinessManagement;

namespace RESTSessionService
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RESTSessionService : IRESTSessionService
    {
        public string OpenSession(string creds)
        {
            Logger.ConsoleLogger.Log("REST Open session with : " + creds);
            if (creds == null || creds == "")
                if (creds == null || creds == "")
                    return "!;POST request is not the right format. Login and/or pass are missing.";

            string[] parts = creds.Split(';');
            Session sess = SessionContainer.ConnectUser(new PLICCredentials() { Password = parts[0], Login = parts[1] });

            if (sess == null)
                return "!;Authentication error.";

            return ".;" + sess.Token;
        }

        public bool RefreshSession(string token)
        {
            Logger.ConsoleLogger.Log("REST Refresh session with : " + token);
            return SessionContainer.RefreshSession(token);
        }

        public void CloseSession(string token)
        {
            Logger.ConsoleLogger.Log("REST Close session with : " + token);
            SessionContainer.CloseSession(token);
        }

        public string CreateUser(string mail, string login, string pass, string race)
        {
            Logger.ConsoleLogger.Log("REST Create user with : " + mail + ", " + login + ", " + pass + ", " + race);
            if (BusinessManagement.AccountManager.CreateAccount(new PLICCredentials() { Login = login, Password = pass },
                new MailAddress(mail), race))
                return ".;User created";
            return "!;Login or mail already in use.";
        }

        public string RegeneratePass(string login, string mail)
        {
            try 
	        {	        
		        BusinessManagement.AccountManager.ChangePassword(login, new MailAddress(mail));
                return "Mail sent.";
	        }
	        catch (Exception)
	        {
		        return "Invalid mail address.";
	        }
        }
    }
}
